const axios = require('axios')
const queryString = require('querystring')
var {client_id, client_secret}=require('../config')
class GithubCol{
    async oauth(ctx){
        // const c = queryString.parse('access_token=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&scope=&token_type=bearer')
        // console.log(c.access_token);
        ctx.body= `
            <h1>Node.js开发仿知乎服务端 深入理解RESTfulAPI</h1>
            <p>Node.js开发仿知乎服务端 深入理解RESTfulAPI</p>
            <a href="/github/login">GitHub登录</a> 
          
        `
    }
    async login(ctx){
        const githubUrl = `https://github.com/login/oauth/authorize?client_id=${client_id}&client_secrets=${client_secret}`
        // 重定向到GitHub认证接口
        ctx.redirect(githubUrl)
    }
    async callback(ctx){
        const code = ctx.query.code
        console.log(code,',,,,,,,,,,,,,,,,,,,,,,,,');
        const data =  await axios.post('https://github.com/login/oauth/access_token',{
            client_id,
            client_secret,
            code
        })
        let access_token_obj =  {}
        if (data.data) {
            console.log(data,',,,,,,,,,,,,,,,,,,,,,,,,');
            access_token_obj =  queryString.parse(data.data)
            console.log(access_token_obj,',,,,,,,,,,,,,,,,,,,,,,,,');
            const userInfo = await axios.get('https://api.github.com/user?access_token=', {
                headers: {
                    "Authorization": "token "+access_token_obj.access_token
                }
            })
            console.log(userInfo, ',,,,,,,,,,,,,,,,,,,,,,,,');
            const {login, avatar_url, bio, html_url} = userInfo
            ctx.body = `
            <h2>你好${login}</h2>
            <img src="${avatar_url}" width="50" alt="">
            <p>介绍${bio}</p>
            <p>github主页${html_url}</p>
            <p>所有信息${JSON.stringify(userInfo,null,4)}</p>
        `
        } else {
            ctx.body = {msg:'获取token失败', data: data}
        }



        // ctx.body = {
        //     code,
        //     res
        // }
    }
}
module.exports = new GithubCol()
